<?php
/**
 * 前台登录 退出操作
 *
 *
 *
 ***/


defined('IN_NWIDC') or exit('Access Invalid!');

class loginControl extends BaseHomeControl {

	public function __construct(){
		parent::__construct();
		Tpl::output('hidden_nctoolbar', 1);
	}

	/**
	 * 登录操作
	 *
	 */
	public function indexOp(){
		Language::read("home_login_index");
		$lang	= Language::getLangContent();
		$model_member	= Model('member');
		//检查登录状态
		$model_member->checkloginMember();
		if ($_GET['inajax'] == 1 && C('captcha_status_login') == '1'){
		    $script = "document.getElementById('codeimage').src='".APP_SITE_URL."/index.php?act=seccode&op=makecode&nchash=".getNchash()."&t=' + Math.random();";
		}
		$result = chksubmit(true,false,'num');
		if ($result !== false){
			if ($result === -11){
				showDialog($lang['login_index_login_illegal'],'','error',$script);
			}elseif ($result === -12){
				showDialog($lang['login_index_wrong_checkcode'],'','error',$script);
			}
			if (process::islock('login')) {
				showDialog($lang['nc_common_op_repeat'],SHOP_SITE_URL,'','error',$script);
			}
			$obj_validate = new Validate();
			$obj_validate->validateparam = array(
				array("input"=>$_POST["user_name"],		"require"=>"true", "message"=>$lang['login_index_username_isnull']),
				array("input"=>$_POST["password"],		"require"=>"true", "message"=>$lang['login_index_password_isnull']),
			);
			$error = $obj_validate->validate();
			if ($error != ''){
			    showDialog($error,SHOP_SITE_URL,'error',$script);
			}
			$array	= array();
			$array['member_name']	= $_POST['user_name'];
			$array['member_passwd']	= md5($_POST['password']);
			$member_info = $model_member->getMemberInfo($array);
			if(is_array($member_info) and !empty($member_info)) {
				if(!$member_info['member_state']){
			        showDialog($lang['login_index_account_stop'],''.'error',$script);
				}
			}else{
			    process::addprocess('login');
			    showDialog($lang['login_index_login_fail'],'','error',$script);
			}

			if(isset($_COOKIE['wechat_openid'])){
				Model('member')->where('member_id = ' . $member_info['member_id'])->update(array('wechat_openid' => $_COOKIE['wechat_openid']['openid']));
				unset($_COOKIE['wechat_openid']);
			}

			// 自动登录
			$member_info['auto_login'] = $_POST['auto_login'];
    		$model_member->createSession($member_info);
			process::clear('login');

			// cookie中的cart存入数据库
			Model('cart')->mergecart($member_info,$_SESSION['store_id']);

			// cookie中的浏览记录存入数据库
			Model('goods_browse')->mergebrowse($_SESSION['member_id'],$_SESSION['store_id']);

			// include_once 'seller_login.php';
			// $m = new seller_loginControl(false);
			// $m->superLogin($_SESSION['member_id']);
			if ($_GET['inajax'] == 1){
			    showDialog('',$_POST['ref_url'] == '' ? 'reload' : $_POST['ref_url'],'js');
			} else {
			    redirect($_POST['ref_url']);
			}
		}else{

			//登录表单页面
			$_pic = @unserialize(C('login_pic'));
			if ($_pic[0] != ''){
				Tpl::output('lpic',UPLOAD_SITE_URL.'/'.ATTACH_LOGIN.'/'.$_pic[array_rand($_pic)]);
			}else{
				Tpl::output('lpic',UPLOAD_SITE_URL.'/'.ATTACH_LOGIN.'/'.rand(1,4).'.jpg');
			}

			if(empty($_GET['ref_url'])) {
			    $ref_url = getReferer();
			    if (!preg_match('/act=login&op=logout/', $ref_url)) {
			     	$_GET['ref_url'] = $ref_url;
			    }
			    if($ref_url != ''){
		     		header('location:index.php?act=login&ref_url=' . urlencode($ref_url));
			    }
			}

			Tpl::output('html_title',C('site_name').' - '.$lang['login_index_login']);
			if ($_GET['inajax'] == 1){
				Tpl::showpage('login_inajax','null_layout');
			}else{
				$GLOBALS['hide_header'] = 1;
				Tpl::showpage('login/default');
			}
		}
	}

	function superLogin($member_id){
		$model_member = Model('member');
		$member_info = $model_member->find($member_id);
		$model_member->createSession($member_info);
	}

	public function wechat_loginOp(){
		$code = $_GET['code'];
		//get openid
		require_wechat();
		$wechat = new WeChat(-1);
		$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$wechat->config['open_appid']}&secret={$wechat->config['open_appsecret']}&code={$_GET['code']}&grant_type=authorization_code";
		$result = $this->curl_https($url);
		$result = json_decode($result,true);
		if(!isset($result['openid'])){
			showMessage('微信请求错误，请联系网站管理员','/shop/index.php?act=login','html','error');
		}
		$minfo = Model('member')->where(array('wechat_openid' => $result['openid']))->find();
		//如果已经绑定，那么直接登录
		if($minfo){
			Model('member')->createSession($minfo);
			// cookie中的cart存入数据库
			Model('cart')->mergecart($minfo,$_SESSION['store_id']);
			// cookie中的浏览记录存入数据库
			Model('goods_browse')->mergebrowse($_SESSION['member_id'],$_SESSION['store_id']);

			header('location:/shop/index.php');
		}
		else{

			$_COOKIE['wechat_openid'] = array(
				'openid' => $result['openid'],
				'time' => time(),
				'nickname' => $result['nickname']
			);
?>
<!DOCTYPE html>
<html lang="en">
			<head>
				<link rel="stylesheet" href="/wap/css/reset.css">
				<meta charset="UTF-8">
				<script src="/data/resource/js/jquery.js"></script>
				<script src='/data/resource/layer/layer.js'></script>
			</head>
<body>
	<style>
		.layui-layer-btn2{
			margin-top: 12px !important;
		}
		..layui-layer-btn1{
			display: none !important;
		}
		.layui-layer-btn a, .layui-layer-dialog .layui-layer-ico, .layui-layer-setwin a{
			vertical-align: bottom;
		}
		body {
			font-family: 'Microsoft Yahei';
			font-size: 12px;
		}
	</style>
	<script>
		layer.confirm('系统检测到您还没有绑定微信',{icon:3,title : '提示',btn:['绑定已有账号','注册新账号','微信登录']},function(index){
			location.href = '/shop/?act=login?open_id=<?php echo $result['openid']?>&nickname=<?php echo $result['nickname']?>';
		},function(){
			location.href = '/shop/?act=login&op=register?open_id=<?php echo $result['openid']?>&nickname=<?php echo $result['nickname']?>';
		});

		$(document).on('click','.layui-layer-btn2',function(){
			location.href = '/shop/?act=login&op=wechat_register?open_id=<?php echo $result['openid']?>&nickname=<?php echo $result['nickname']?>';
		});
	</script>
</body>

			</html>
<?php
		}
		exit;
		echo $code;
		// $js = new JsApiPay();
		// $open_id = $js->GetOpenid();
		// echo $open_id;
		print_r($_POST);
	}

	function wechat_registerOp(){
		if(!isset($_GET['open_id'])){
			showMessage('微信请求错误，请联系网站管理员','/shop/index.php?act=login','html','error');
		}


		// $open_id = $_SESSION['wechat_openid']['openid'];
		$open_id = $_GET['openid'];
		$um = Model('member');
        $insert_array = array();
        $member_name = "wechat_" . $_GET['nickname'] . rand(10000000,99999999);
        $insert_array['member_name']	= trim($member_name);
		$insert_array['member_passwd']	= trim(1234567);
		$insert_array['member_email']	= trim('');
		$insert_array['member_truename']= trim('');
		$insert_array['member_sex'] 	= trim('');
		$insert_array['member_qq'] 		= trim('');
		$insert_array['member_ww']		= trim('');
		// $insert_array['wechat_openid'] = $open_id;
		$result = $um->addMember($insert_array);
		if($result){
			$member_info = $um->getMemberInfo(array('member_name' => $member_name,'member_passwd' => md5(1234567)));
			Model('member')->where(array('member_name' => $member_name))->update(array('wechat_openid' => $open_id));

			Model('member')->createSession($member_info);
			// cookie中的cart存入数据库
			Model('cart')->mergecart($member_info,$_SESSION['store_id']);
			// cookie中的浏览记录存入数据库
			Model('goods_browse')->mergebrowse($_SESSION['member_id'],$_SESSION['store_id']);

			unset($_COOKIE['wechat_openid']);
			header('location:/shop/index.php?act=member_order');
		}

	}

	function curl_https($url, $data=array(), $header=array(), $timeout=30){

	    $ch = curl_init();
	    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
	    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true);  // 从证书中检查SSL加密算法是否存在
	    curl_setopt($ch, CURLOPT_URL, $url);
	    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
	    curl_setopt($ch, CURLOPT_POST, true);
	    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
	    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);

	    $response = curl_exec($ch);

	    if($error=curl_error($ch)){
	        die($error);
	    }

	    curl_close($ch);

	    return $response;

	}

	function ajaxLoginOp(){
		$model_member	= Model('member');
		if(isset($_SESSION) && $_SESSION['is_login'] == 1){
			exit(json_encode(array('status' => 'failed', 'msg' => '登录失败，账号已登录！')));
		}

		$_POST['user_name'] = trim($_POST['user_name']);
		//如果存在商家
		if($_POST['loginType'] == 1){
			//检查是否有商家资格
			$member_id = getOne("select member_id from ra_member where member_name = '$_POST[user_name]'");
			$is_seller = getOne("select count(*) from ra_seller where member_id = $member_id");
			if(!$is_seller){
				exit(json_encode(array('status' => 'failed', 'msg' => '登录失败，该账号未开通商家！')));
			}
		}

		$obj_validate = new Validate();
		$obj_validate->validateparam = array(
			array("input"=>$_POST["user_name"],	"require"=>"true", "message"=>$lang['login_index_username_isnull']),
			array("input"=>$_POST["password"],	"require"=>"true", "message"=>$lang['login_index_password_isnull']),
		);
		$error = $obj_validate->validate();
		if ($error != ''){
		    exit(json_encode(array('status' => 'failed','msg' => $error)));
		}
		$array	= array();
		$array['member_name']	= $_POST['user_name'];
		$array['member_passwd']	= md5($_POST['password']);
		$member_info = $model_member->getMemberInfo($array);
		if(is_array($member_info) and !empty($member_info)) {
			if(!$member_info['member_state']){
				exit(json_encode(array('status' => 'failed', 'msg' => '登录失败，账号或密码错误！')));
			}
		}else{
			exit(json_encode(array('status' => 'failed', 'msg' => '登录失败，账号或密码错误！')));
		    // showDialog($lang['login_index_login_fail'],'','error',$script);
		}
		$model_member->createSession($member_info);

		// cookie中的cart存入数据库
		Model('cart')->mergecart($member_info,$_SESSION['store_id']);

		// cookie中的浏览记录存入数据库
		Model('goods_browse')->mergebrowse($_SESSION['member_id'],$_SESSION['store_id']);

		//如果有这个商家且登录成功
		if($_POST['loginType'] == 1){
			include_once 'seller_login.php';
			$m = new seller_loginControl(false);
			$m->superLogin($_SESSION['member_id']);
		}

		exit(json_encode(array('status' => 'success','msg' => '登录成功')));
	}

	/**
	 * 退出操作
	 *
	 * @param int $id 记录ID
	 * @return array $rs_row 返回数组形式的查询结果
	 */
	public function logoutOp(){
		Language::read("home_login_index");
		$lang	= Language::getLangContent();
		// 清理消息COOKIE
		setNcCookie('msgnewnum'.$_SESSION['member_id'],'',-3600);
		setNcCookie('auto_login', '', -3600);
		setNcCookie('cart_goods_num','',-3600);
		@session_unset();
		@session_destroy();
		setNcCookie('cart_goods_num','',-3600);
		if(empty($_GET['ref_url'])){
			$ref_url = getReferer();
		}else {
			$ref_url = $_GET['ref_url'];
		}
		exit(json_encode(array('status' => 'success', 'msg' => '退出成功')));
		// redirect('index.php?act=login&ref_url='.urlencode($ref_url));
	}

	/**
	 * 会员注册页面
	 *
	 * @param
	 * @return
	 */
	public function registerOp() {
		Language::read("home_login_register");
		$lang	= Language::getLangContent();
		$model_member	= Model('member');
		$model_member->checkloginMember();
		Tpl::output('html_title',C('site_name').' - '.$lang['login_register_join_us']);
		// Tpl::showpage('register');
		// exit;
		$GLOBALS['hide_header'] = 1;
		Tpl::showpage('register/default');
	}

	/**
	 * 会员添加操作
	 *
	 * @param
	 * @return
	 */
	public function usersaveOp() {
		//重复注册验证
		if (process::islock('reg')){
			showDialog(Language::get('nc_common_op_repeat'));
		}
		Language::read("home_login_register");
		$lang	= Language::getLangContent();
		$model_member	= Model('member');
		$model_member->checkloginMember();

		//检查手机号码
		$mobile = $_SESSION['mobile_code']['mobile'];
		if(empty($mobile)){
			showDialog('请输入正确的手机号码','','error');
		}

		if(!check_mobile_code($_POST['mobile_phone'],$_POST['mobile_verify'])){
			showDialog('请输入正确的短信验证码','','error');
		}

		$same = Model('member')->where(array('member_mobile' => trim($_POST['mobile_phone']), 'member_mobile_bind' => 1))->count();
		if($same){
			showDialog('该手机号码已被注册','','error');
		}


		$result = chksubmit(true,C('captcha_status_register'),'num');
		if ($result){
			if ($result === -11){
				showDialog($lang['invalid_request'],'','error');
			}elseif ($result === -12){
				showDialog($lang['login_usersave_wrong_code'],'','error');
			}
		} else {
		    // showDialog($lang['invalid_request'],'','error');
		}
        $register_info = array();
        $register_info['username'] = $_POST['user_name'];
        $register_info['password'] = $_POST['password'];
        $register_info['password_confirm'] = $_POST['password_confirm'];
        // $register_info['email'] = $_POST['email'];
        $register_info['is_buy'] = 0;
        $member_info = $model_member->register($register_info);
        if(!isset($member_info['error'])) {

        	if(isset($_COOKIE['wechat_openid'])){
				Model('member')->where('member_id = ' . $member_info['member_id'])->update(array('wechat_openid' => $_COOKIE['wechat_openid']['openid']));
				unset($_COOKIE['wechat_openid']);
			}

            $model_member->createSession($member_info,true);
			process::addprocess('reg');

			// cookie中的cart存入数据库
			Model('cart')->mergecart($member_info,$_SESSION['store_id']);

			// cookie中的浏览记录存入数据库
			Model('goods_browse')->mergebrowse($_SESSION['member_id'],$_SESSION['store_id']);

			if(!empty($_POST['proxy_id'])){
				Model()->table('proxy')->insert(array(
					'member_id' => $_SESSION['member_id'],
					'time' => time(),
					'parent_id' => $_POST['proxy_id'],
					'is_guest' => 1
				));
				// Model()->table('proxy_apply')->insert(array(
				// 	'proxy_member_id' => $_POST['proxy_id'],
				// 	'contact' => $_POST['contact'],
				// 	'time' => time(),
				// 	'msg' => $_POST['msg']
				// ));
			}

			if(!empty($_POST['invite_code'])){
				$member_id = base64_decode(trim($_POST['invite_code'])) >> 16;
				if($member_id > 0){
					$proxy_info = Model('proxy')->where(array('member_id' => $member_id))->find();
					if($proxy_info){
						Model()->table('proxy')->insert(array(
							'member_id' => $_SESSION['member_id'],
							'time' => time(),
							'parent_id' => member_id,
							'is_guest' => 1
						));
					}
				}
			}


			//保存手机
			Model()->table('member')->where(array('member_id' => $_SESSION['member_id']))->update(array(
				'member_mobile' => trim($_POST['mobile_phone']),
				'member_mobile_bind' => 1
			));

			// $sql = "update ra_member set is_buy = 0 where member_id = $_SESSION[member_id]";
			// getOne($sql);
			// Model()->query($sql);
			// die($sql);
			// exit;1

			//Model("member")->where(array('member_id' => $_SESSION['member_id']))->update(array("is_buy" => 0));

			$_POST['ref_url']	= (strstr($_POST['ref_url'],'logout')=== false && !empty($_POST['ref_url']) ? $_POST['ref_url'] : 'index.php?act=member_information&op=member');
			redirect($_POST['ref_url']);
        } else {
			showDialog($member_info['error']);
        }
	}
	/**
	 * 会员名称检测
	 *
	 * @param
	 * @return
	 */
	public function check_memberOp() {
			/**
		 	* 实例化模型
		 	*/
			$model_member	= Model('member');

			$check_member_name	= $model_member->getMemberInfo(array('member_name'=>$_GET['user_name']));
			if(is_array($check_member_name) and count($check_member_name)>0) {
				echo 'false';
			} else {
				echo 'true';
			}
	}

	/**
	 * 电子邮箱检测
	 *
	 * @param
	 * @return
	 */
	public function check_emailOp() {
		$model_member = Model('member');
		$check_member_email	= $model_member->getMemberInfo(array('member_email'=>$_GET['email']));
		if(is_array($check_member_email) and count($check_member_email)>0) {
			echo 'false';
		} else {
			echo 'true';
		}
	}

	/**
	 * 忘记密码页面
	 */
	public function forget_passwordOp(){
		/**
		 * 读取语言包
		 */
		Language::read('home_login_register');
		$_pic = @unserialize(C('login_pic'));
		if ($_pic[0] != ''){
			Tpl::output('lpic',UPLOAD_SITE_URL.'/'.ATTACH_LOGIN.'/'.$_pic[array_rand($_pic)]);
		}else{
			Tpl::output('lpic',UPLOAD_SITE_URL.'/'.ATTACH_LOGIN.'/'.rand(1,4).'.jpg');
		}
		Tpl::output('html_title',C('site_name').' - '.Language::get('login_index_find_password'));
		Tpl::showpage('find_password');
	}

	/**
	 * 找回密码的发邮件处理
	 */
	public function find_passwordOp(){
		$mobile = $_POST['mobile'];
		$code = $_POST['code'];
		$password = $_POST['password'];
		$confirm_password = $_POST['confirm_password'];

		//判断验证码是否正确
		if(!($_SESSION['mobile_code']['mobile'] == $mobile && $_SESSION['mobile_code']['code'] == $code)){
			showDialog('验证码错误');
			return false;
		}

		if($password != $password_confirm){
			showDialog('密码输入不一致，请重新输入');
			return false;
		}

		//查询是否有会员
		$member_info = Model('member')->where(array('member_mobile'=>$mobile))->find();
		if(empty($member_info)){
			showDialog('对不起没有查询到该会员，请检查手机号是否输入正确');
			return false;
		}
		else{
			$result = Model('member')->editMember(array('member_passwd'=>md5($password)));
			if($result){
				showDialog('密码修改成功');
				return false;
			}
		}

		exit;
		Language::read('home_login_register');
		$lang	= Language::getLangContent();

		$result = chksubmit();
		if ($result !== false){
		    if ($result === -11){
		        showDialog('非法提交');
		    }elseif ($result === -12){
		        showDialog('验证码错误');
		    }
		}

		if(empty($_POST['username'])){
			showDialog($lang['login_password_input_username']);
		}

		if (process::islock('forget')) {
		    showDialog($lang['nc_common_op_repeat'],'reload');
		}

		$member_model	= Model('member');
		$member	= $member_model->getMemberInfo(array('member_name'=>$_POST['username']));
		if(empty($member) or !is_array($member)){
		    process::addprocess('forget');
			showDialog($lang['login_password_username_not_exists'],'reload');
		}

		if(empty($_POST['email'])){
			showDialog($lang['login_password_input_email'],'reload');
		}

		if(strtoupper($_POST['email'])!=strtoupper($member['member_email'])){
		    process::addprocess('forget');
			showDialog($lang['login_password_email_not_exists'],'reload');
		}
		process::clear('forget');
		//产生密码
		$new_password	= random(15);
		if(!($member_model->editMember(array('member_id'=>$member['member_id']),array('member_passwd'=>md5($new_password))))){
			showDialog($lang['login_password_email_fail'],'reload');
		}

		$model_tpl = Model('mail_templates');
		$tpl_info = $model_tpl->getTplInfo(array('code'=>'reset_pwd'));
		$param = array();
		$param['site_name']	= C('site_name');
		$param['user_name'] = $_POST['username'];
		$param['new_password'] = $new_password;
		$param['site_url'] = SHOP_SITE_URL;
		$subject	= ncReplaceText($tpl_info['title'],$param);
		$message	= ncReplaceText($tpl_info['content'],$param);

		$email	= new Email();
		$result	= $email->send_sys_email($_POST["email"],$subject,$message);
		showDialog('新密码已经发送至您的邮箱，请尽快登录并更改密码！','','succ','',5);
	}

	/**
	 * 邮箱绑定验证
	 */
	public function bind_emailOp() {
	   $model_member = Model('member');
	   $uid = @base64_decode($_GET['uid']);
	   $uid = decrypt($uid,'');
	   list($member_id,$member_email) = explode(' ', $uid);

	   if (!is_numeric($member_id)) {
	       showMessage('验证失败',SHOP_SITE_URL,'html','error');
	   }

	   $member_info = $model_member->getMemberInfo(array('member_id'=>$member_id),'member_email');
	   if ($member_info['member_email'] != $member_email) {
	       showMessage('验证失败',SHOP_SITE_URL,'html','error');
	   }

	   $member_common_info = $model_member->getMemberCommonInfo(array('member_id'=>$member_id));
	   if (empty($member_common_info) || !is_array($member_common_info)) {
	       showMessage('验证失败',SHOP_SITE_URL,'html','error');
	   }
	   if (md5($member_common_info['auth_code']) != $_GET['hash'] || TIMESTAMP - $member_common_info['send_acode_time'] > 24*3600) {
	       showMessage('验证失败',SHOP_SITE_URL,'html','error');
	   }

	   $update = $model_member->editMember(array('member_id'=>$member_id),array('member_email_bind'=>1));
	   if (!$update) {
	       showMessage('系统发生错误，如有疑问请与管理员联系',SHOP_SITE_URL,'html','error');
	   }

	   $data = array();
	   $data['auth_code'] = '';
	   $data['send_acode_time'] = 0;
	   $update = $model_member->editMemberCommon($data,array('member_id'=>$_SESSION['member_id']));
	   if (!$update) {
	       showDialog('系统发生错误，如有疑问请与管理员联系');
	   }
	   showMessage('邮箱设置成功','index.php?act=member_security&op=index');

	}
}
